package team.kirohuji.shiro.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;

import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import team.kirohuji.domain.system.UrlFilter;
import team.kirohuji.repository.jpa.system.UrlFilterRepository;

@Service
public class ShiroFilerChainManager {

	@Autowired
	private CustomDefaultFilterChainManager filterChainManager;

	private Map<String, NamedFilterList> defaultFilterChains;
	@Autowired
	private UrlFilterRepository urlFilterRepository;

	@PostConstruct
	public void init() {
		System.out.println("...初始化ShiroFilerChainManager，这个类的目的是要把数据库里的过滤器记录加载到现在的过滤器中...");
		defaultFilterChains = new HashMap<String, NamedFilterList>(filterChainManager.getFilterChains());
		System.out.println("原来是没有第一次加载这个方法，但是现在测试，需要第一次加载将执行initFilterChains方法，这个方法就是从数据库中加载数据");
		initFilterChains(urlFilterRepository.findAll());
	}

	public void initFilterChains(List<UrlFilter> urlFilters) {
		System.out.println("执行ShiroFilerChainManager的initFilterChains操作，目的是将之前的过滤器清除");
		// 1、首先删除以前老的filter chain并注册默认的
		filterChainManager.getFilterChains().clear();
		if (defaultFilterChains != null) {
			System.out.println("默认的defaultFilterChains:");
			for (Entry<String, NamedFilterList> m : defaultFilterChains.entrySet()) {
				System.out.println(m.getKey());
			}
			filterChainManager.getFilterChains().putAll(defaultFilterChains);
		}

		// 2、循环URL Filter 注册filter chain
		for (UrlFilter urlFilter : urlFilters) {
			String url = urlFilter.getUrl();
			// 注册roles filter
			if (!StringUtils.isEmpty(urlFilter.getRoles())) {
				filterChainManager.addToChain(url, "roles", urlFilter.getRoles());
			}
			// 注册perms filter
			if (!StringUtils.isEmpty(urlFilter.getPermissions())) {
				filterChainManager.addToChain(url, "perms", urlFilter.getPermissions());
			}
		}
		System.out.println("执行完成，现在将显示已经有的filters");
		for (Entry<String, NamedFilterList> m : filterChainManager.getFilterChains().entrySet()) {
			System.out.println(m.getKey());
		}
	}

}
